#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2018/11/15 10:05
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : 中级-两数相除.py
# @Software: PyCharm

from utils.main import main, opt_list


class Solution:
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """

        def sig(x):
            return 1 if x >= 0 else -1

        def format_ans(a):  # 需要考虑答案溢出问题
            u = 2 ** 31 - 1
            du = -u - 1
            if a > u:
                return u
            elif a < du:
                return du
            return a

        s1 = sig(dividend)
        dividend *= s1
        s2 = sig(divisor)
        divisor *= s2
        s_ans = s1 * s2
        ans = 0
        p = 1
        dp = divisor
        while dividend > dp:
            dp <<= 1
            p <<= 1
        if dividend == dp:
            return format_ans(p * s_ans)
        dp >>= 1
        p >>= 1
        while p and dividend > 0:
            if dividend >= dp:
                dividend -= dp
                ans += p
            dp >>= 1
            p >>= 1
        return format_ans(ans * s_ans)


def opt(dividend, divisor):
    solve = Solution()
    print('params:', dividend, divisor)
    print('ans:', solve.divide(dividend, divisor))


def opt0():
    opt(102, 22)


def opt1():
    opt(-102, 22)


def opt2():
    opt(-1, 1)


def opt3():
    opt(-2147483648, -1)
    print(-2147483648/-1)
    print(-2147483648//-1)


opt_list.append(opt0)
opt_list.append(opt1)
opt_list.append(opt2)
opt_list.append(opt3)


if __name__ == '__main__':
    main()
